<template>
  <div style="color: #000">
    <el-tabs
      v-model="activeName"
      :tab-position="tabPosition"
      style="height: 100vh"
      @tab-click="tabClick"
    >
      <el-tab-pane label="Tally Task" name="Tally_Task">
        <div class="topic">Tally Task</div>
        <div class="task_area">
          <div style="text-align: right; margin-top: 20px">
            <el-form
              :inline="true"
              :model="formInline"
              :rules="updateRules"
              ref="updateRules"
              class="demo-form-inline"
            >
              <el-form-item label="Station" prop="WbId">
                <el-select
                  v-model="formInline.WbId"
                  placeholder="Please select"
                  clearable
                >
                  <el-option
                    v-for="item in TallyManageList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="SKU id" prop="SkuId">
                <el-input
                  v-model="formInline.SkuId"
                  placeholder="Please enter"
                  clearable
                ></el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="TallyManagePut()"
                  >Query</el-button
                >
              </el-form-item>
              <el-form-item style="margin-right: 0">
                <el-button @click="Clear" type="danger" plain>Clear</el-button>
              </el-form-item>
            </el-form>
          </div>
          <div>
            <el-table
              ref="multipleTable"
              :data="tableData"
              tooltip-effect="dark"
              style="width: 100%; max-height: 62vh; overflow: auto"
              border
              @selection-change="handleSelectionChange"
            >
              <el-table-column type="selection" width="55"> </el-table-column>
              <el-table-column label="tote id">
                <template slot-scope="scope">{{ scope.row.tote_id }}</template>
              </el-table-column>
              <el-table-column prop="box_code" label="compartment id">
              </el-table-column>
              <el-table-column
                prop="location_id"
                label="location id"
                show-overflow-tooltip
              >
              </el-table-column>
              <el-table-column prop="qty" label="QTY" show-overflow-tooltip>
              </el-table-column>
            </el-table>
            <el-pagination
              style="margin: 10px 0 0 0"
              background
              :page-sizes="[5, 10, 20]"
              @current-change="handleCurrentChange"
              @size-change="handleSizeChange"
              layout="prev, pager, next, sizes"
              :total="pagination.total_count"
            >
            </el-pagination>
          </div>
          <div style="text-align: right">
            <el-button
              style="transform: scale(1.2)"
              type="primary"
              round
              @click="TallyManagePost"
              >submit</el-button
            >
          </div>
        </div>
      </el-tab-pane>

      <el-tab-pane label="Location Audit" name="Location_Audit">
        <div class="topic">Location Audit</div>
        <div class="Audit_area">
          <div style="width: 20%; margin-top: 20px">
            <div style="font-weight: 500; margin-bottom: 8px">Location ID</div>
            <el-input
              v-model="taskLoc"
              placeholder="Enter location ID (e.g.RA-1-1-1)"
              clearable
            ></el-input>
            <div>
              <el-button
                style="transform: scale(1); margin-top: 20px; width: 100%"
                type="primary"
                @click="TaskLocPost"
                icon="el-icon-position"
                >Submit Task</el-button
              >
            </div>
          </div>
          <div style="width: 75%">
            <div class="audit-list">
              <div
                style="font-weight: 500; font-size: 24px; margin-bottom: 10px"
              >
                Active Tasks
              </div>
              <div>
                <el-tag>{{ totalCount }} tasks</el-tag>
              </div>
            </div>
            <el-table
              ref="multipleTable"
              :data="tableData"
              tooltip-effect="dark"
              style="width: 100%; max-height: 62vh; overflow: auto"
              border
              @selection-change="handleSelectionChange"
            >
              <el-table-column type="selection" width="55"> </el-table-column>
              <el-table-column label="Task ID">
                <template slot-scope="scope">{{ scope.row.tote_id }}</template>
              </el-table-column>
              <el-table-column prop="box_code" label="Location ID">
              </el-table-column>
              <el-table-column
                prop="location_id"
                label="Created At"
                show-overflow-tooltip
              >
              </el-table-column>
              <el-table-column prop="qty" label="Status" show-overflow-tooltip>
              </el-table-column>
            </el-table>
            <el-pagination
              style="margin: 10px 0 0 0"
              background
              :page-sizes="[5, 10, 20]"
              @current-change="handleCurrentChange2"
              @size-change="handleSizeChange2"
              layout="prev, pager, next, sizes"
              :total="totalCount"
            >
            </el-pagination>
          </div>
        </div>
      </el-tab-pane>

      <el-tab-pane label="Station Configuration" name="Station_Controller">
        <div class="topic">Station Configuration</div>
        <div class="station_area">
          <div
            class="station_area_list"
            v-for="(item, index) in StationList"
            :key="index"
          >
            <div class="station_area_txt">{{ item.WHAreaId }}</div>
            <el-select
              style="margin: 0 30px"
              v-model="item.WbType"
              placeholder="请选择"
              @change="currentWHAreaId(item.WbId)"
            >
              <el-option
                v-for="item in OptionsComputed(item.WHAreaId)"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
            <el-switch
              v-model="item.Status"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="switchWHAreaId(item.WbId)"
            >
            </el-switch>
          </div>
        </div>
      </el-tab-pane>

      <el-tab-pane label="Call Empty Totes" name="Call_Empty_Totes">
        <div class="topic">Call Empty Totes</div>
        <div class="top_area">
          <div class="top_left">
            <div class="Call_Empty">Call Empty Totes</div>
            <div class="Call_Empty_num">
              <!-- <el-input-number
                v-model.number="CallEmptyNum"
                @change="handleChange"
                ref="inputNumber"
                :min="1"
                :step="10"
                @input="validateInteger"
                label="描述文字"
              ></el-input-number> -->
              <el-input
                v-model="CallEmptyNum"
                autocomplete="off"
                @input="validateInteger"
              ></el-input>
            </div>
          </div>
          <div>
            <div>
              <div class="Current_Empties">Current Empties</div>
              <div class="Current_Empties_num">{{ CurrentEmpties }}</div>
            </div>
            <div class="submit">
              <el-button
                style="transform: scale(1.2); width: 100%"
                type="primary"
                round
                @click="CallEmptyPut"
                >submit</el-button
              >
            </div>
          </div>
        </div>
      </el-tab-pane>

      <el-tab-pane
        label="User Permission Management"
        name="User_Permission_Management"
      >
        <div class="topic">User Permission Management</div>
        <div class="top_area">
          <Login />
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
import SelWorkBench from "@/components/SelWorkBench.vue";
import Login from "./Login.vue";
import ScanComponent from "./ScanComponent.vue";
import { columns, columnsS } from "./tableColumns";
import { api } from "@/utils/api";
import { comparedArr, removeListItem } from "@/utils/tools";
import axios from "axios";
import _ from "lodash";
import locale from "ant-design-vue/es/date-picker/locale/zh_CN";
import moment from "moment";
import { InitLoc } from "@/utils/sortLoc";
import { mockSort } from "./mockSortData";
export default {
  name: "WorkBench",
  components: {
    Login,
  },
  props: {
    msg: String,
  },
  computed: {
    userName: () => {
      return sessionStorage.getItem("userName");
    },
    OptionsComputed() {
      return function (str) {
        let option = [];
        if (str.indexOf("IC") != -1) {
          option = this.ic_options;
        } else {
          option = this.options;
        }
        return option;
      };
    },
  },
  data: () => {
    return {
      updateRules: {
        SkuId: [
          { required: true, message: "Sku ID Required", trigger: "change" },
        ],
        WbId: [
          {
            required: true,
            message: "station id is required",
            trigger: "change",
          },
        ],
      },
      taskLoc: "",
      tabPosition: "left",
      activeName: "Tally_Task",
      CurrentEmpties: "",
      tabName: [
        "Tally_Task",
        "Location_Audit",
        "Station_Controller",
        "Call_Empty_Totes",
        "User_Permission_Management",
      ],
      formInline: {
        WbId: "",
        SkuId: "",
      },
      tableData: [],
      multipleSelection: [],
      options: [
        {
          value: "INVENTORY",
          label: "INVENTORY",
        },
        {
          value: "OUT",
          label: "OUT",
        },
        {
          value: "TAY",
          label: "TAY",
        },
      ],
      ic_options: [
        {
          value: "INVENTORY",
          label: "INVENTORY",
        },
        {
          value: "TAY",
          label: "TAY",
        },
      ],
      UserId: "",
      CallEmptyNum: 1,
      value: true,
      StationList: [],
      TallyManageList: [],
      pagination: {
        page_num: 1,
        page_size: 10,
        total_count: 100,
      },
      pageIndex: 0,
      pageSize: 10,
      totalCount: 0,
    };
  },
  watch: {
    CallEmptyNum: {
      handler(newVal, oldVal) {
        console.log("DDD", newVal);
      },
      deep: true,
      immediate: true,
    },
    activeName: {
      handler(newVal, oldVal) {
        console.log("activeName", newVal);
        // "Tally_Task", "Station_Controller", "Call_Empty_Totes"
        if (newVal == "Tally_Task") {
          if (this.UserId) {
            this.TallyManageGet();
          } else {
            this.LoginPost().then((res) => {
              if (res) {
                this.TallyManageGet();
              }
            });
          }
        }
        if (newVal == "Location_Audit") {
          this.TaskLocGet();

          if (this.UserId) {
            this.TaskLocGet();
          } else {
            this.LoginPost().then((res) => {
              if (res) {
                this.TaskLocGet();
              }
            });
          }
        }
        if (newVal == "Station_Controller") {
          if (!this.UserId) {
            this.LoginPost().then((res) => {
              if (res) {
                this.StationGet();
              }
            });
          } else {
            this.StationGet();
          }
        }
        if (newVal == "Call_Empty_Totes") {
          if (!this.UserId) {
            this.LoginPost().then((res) => {
              if (res) {
                this.CallEmptyGet();
              }
            });
          } else {
            this.CallEmptyGet();
          }
        }
      },
      deep: true,
      immediate: true,
    },
  },
  async mounted() {
    // if (sessionStorage.getItem("activeName"))
    //   this.activeName = sessionStorage.getItem("activeName");
    // this.LoginPost().then((res) => {
    //   if (res) {
    //     this.StationGet();
    //     this.TallyManageGet();
    //     this.CallEmptyGet();
    //   }
    // });
  },
  methods: {
    // 输入框不能输入小数限制
    validateInteger(val) {
      this.CallEmptyNum = val.replace(/[^\d]/g, "");
    },
    LoginPost() {
      return new Promise(async (resolve, reject) => {
        const params = { WbId: "W1", UserPwd: "8888", UserId: "zww" };
        let [ERR, GRES] = await api.LoginPost(params);
        console.log("LoginPost", GRES);
        if (GRES.code == 0) {
          this.UserId = GRES.data.UserId;
          resolve(true);
        } else {
          reject(false);
        }
      });
    },

    tabClick(tab, event) {
      this.activeName = this.tabName[tab.index];
      sessionStorage.setItem("activeName", this.activeName);
      // tabName:['Tally_Task','Station_Controller','Call_Empty_Totes'],
    },
    async currentWHAreaId(WbId) {
      let item = this.StationList.find((f) => f.WbId == WbId);
      // console.log("currentWHAreaId", item.WbType);
      const params = { WbId, WbType: item.WbType, UserId: this.UserId };
      let [ERR, GRES] = await api.StationPut(params);
      console.log("StationPut", GRES);
      if (GRES.code === 0) {
        this.$message.success("success");
      }
      this.StationGet();
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      this.pagination.page_num = val;
      this.TallyManagePut(val, this.pagination.page_size);
    },
    handleCurrentChange2(val) {
      // console.log(`当前页: ${val}`);
      this.pagination.page_num = val;
      this.TaskLocGet(val, this.pageSize);
    },
    handleSizeChange(val) {
      this.pagination.page_size = val;
      this.TallyManagePut(this.pagination.page_num, val);
      // console.log(`每页 ${val} 条`);
    },
    handleSizeChange2(val) {
      this.pagination.page_size = val;
      this.TaskLocGet(this.pageIndex, val);
      // console.log(`每页 ${val} 条`);
    },
    TallyManagePut(page_num = 1, page_size = 10) {
      this.$refs.updateRules.validate(async (valid) => {
        if (valid) {
          this.formInline.SkuId = this.formInline.SkuId.replace(/[^\d]/g, "");
          const params = {
            sku_id: this.formInline.SkuId,
            UserId: this.UserId,
            page_num,
            page_size,
          };
          let [ERR, GRES] = await api.TallyManagePut(params);
          console.log("TallyManagePut", GRES);
          if (GRES.code === 0) {
            this.tableData = GRES.data;
            if (GRES.data.length > 0) {
              this.pagination.total_count = GRES.data[0].total_count;
            }
            // this.$message.success("success");
          }
        }
      });
    },
    async TaskLocGet(pageIndex = 0, pageSize = 10) {
      const params = { pageIndex, pageSize };
      let [ERR, GRES] = await api.TaskLocGet(params);
      console.log("TaskLocGet", GRES);
      if (GRES.code === 0) {
        this.totalCount = GRES.data.totalCount;
      }
    },
    async TaskLocPost() {
      const params = { LocationId: this.taskLoc };
      let [ERR, GRES] = await api.TaskLocPost(params);
      console.log("TaskLocPost", GRES);
      if (GRES.code == 0) {
        this.$message.success("success");
      } else {
        reject(false);
      }
    },

    // 10000012
    async TallyManagePost() {
      const selToteList = this.multipleSelection.filter((m) => m.tote_id);
      const toteList = [...new Set(selToteList)];
      if (toteList.length < 2) {
        this.$message.warning("a tally order should choose at least two totes");
        return;
      }
      const params = {
        sku: this.formInline.SkuId,
        wb_id: this.formInline.WbId,
        user_id: this.UserId,
        UserId: this.UserId,
        tallys: this.multipleSelection,
      };
      const sum = this.multipleSelection.reduce((pre, cur) => {
        return pre + cur.qty;
      }, 0);
      if (sum > 10) {
        this.$confirm(
          "Too many items chose, pls ensure the volume of this item is able to consolidate into one compartment. IF YES click 'continue', OR 'cancel?",
          "warning",
          {
            confirmButtonText: "continue",
            cancelButtonText: "cancel",
            type: "warning",
            confirmButtonClass: "confirmClass",
          }
        ).then(async () => {
          let [ERR, GRES] = await api.TallyManagePost(params);
          if (GRES.code === 0) {
            this.TallyManagePut(
              this.pagination.page_num,
              this.pagination.page_size
            );
            this.$message.success("success");
          }
        });
      } else {
        let [ERR, GRES] = await api.TallyManagePost(params);
        if (GRES.code === 0) {
          this.TallyManagePut(
            this.pagination.page_num,
            this.pagination.page_size
          );
          this.$message.success("success");
        }
      }
    },

    Clear() {
      this.formInline.SkuId = "";
      this.tableData = [];
    },

    async switchWHAreaId(WbId) {
      let item = this.StationList.find((f) => f.WbId == WbId);
      let status = item.Status;
      let Status = status ? 1 : 0;
      console.log("switchWHAreaId", item.Status, !item.Status, Status);
      const params = { WbId, Status, UserId: this.UserId };
      let [ERR, GRES] = await api.StationPost(params);
      if (GRES.code === 0) {
        this.$message.success("success");
      }
      this.StationGet();
      this.TallyManageGet();
    },

    async CallEmptyPut() {
      if (this.CallEmptyNum > 200) {
        this.$message.warning(
          "for efficiency, pls do not create too many tasks each hour"
        );
        return;
      }
      const params = { Qty: this.CallEmptyNum, UserId: this.UserId, WbId: "" };
      let [ERR, GRES] = await api.CallEmptyPut(params);
      console.log("CallEmptyPut", GRES);
      if (GRES.code === 0) {
        this.$message.success("success");
      }
      this.CallEmptyGet();
    },

    async StationGet() {
      const params = { UserId: this.UserId };
      let [ERR, GRES] = await api.StationGet(params);
      console.log("StationGet", GRES);
      if (GRES.code === 0) {
        this.StationList = GRES.data.map((m) => ({
          ...m,
          Status: m.Status == 1 ? true : false,
        }));
      }
    },

    async TallyManageGet() {
      const params = { UserId: this.UserId };
      let [ERR, GRES] = await api.TallyManageGet(params);
      console.log("TallyManageGet", GRES);
      if (GRES.code === 0) {
        this.TallyManageList = GRES.data.map((m) => ({
          ...m,
          label: m.WbId,
          value: m.WbId,
        }));
        this.formInline.WbId =
          this.TallyManageList[0] && this.TallyManageList[0].value;
      }
    },

    async CallEmptyGet() {
      const params = { UserId: this.UserId };
      let [ERR, GRES] = await api.CallEmptyGet(params);
      console.log("CallEmptyGet", GRES);
      if (GRES.code === 0) {
        this.CurrentEmpties = GRES.data[0]?.total_qty;
      }
    },

    handleInput(val) {
      // 如果输入的值不是正整数（例如，输入了0、小数或负数），则重置为前一个有效值
      // if (val <= 0 || !Number.isInteger(val)) {
      //   this.$message.error("请输入正整数");
      //   console.log("请输入正整数a", this.$refs.inputNumber);
      //   // this.$refs.inputNumber.setValue(this.CallEmptyNum); // 假设你有一个ref来引用el-input-number
      // } else {
      //   this.CallEmptyNum = val;
      // }
    },
    handleChange(value) {
      //   console.log("handleChange!");
      //   if (value <= 0 || !Number.isInteger(value)) {
      //     this.$message.error("请输入正整数");
      //     // 你可以尝试使用 nextTick 来确保 DOM 更新后再设置值，但这可能不是必要的
      //     // 因为 v-model.number 通常会确保值是数字
      //     this.numberValue = this.numberValue > 0 ? this.numberValue : 1; // 重置为1或其他合适的值
      //   }
    },
    onSubmit() {
      console.log("submit!");
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
  },
};
</script>

<style scoped lang="scss">
.confirmClass {
  background: red;
}
/* 自定义整个滚动条 */
::-webkit-scrollbar {
  width: 12px; /* 设置滚动条的宽度 */
}

/* 自定义滚动条轨道 */
::-webkit-scrollbar-track {
  background: #f1f1f1; /* 设置轨道的背景颜色 */
}

/* 自定义滚动条的滑块（thumb） */
::-webkit-scrollbar-thumb {
  background: #888; /* 设置滑块的背景颜色 */
}

/* 当滑块悬停或活动时，可以添加更多样式 */
::-webkit-scrollbar-thumb:hover {
  background: #555; /* 设置滑块在悬停状态下的背景颜色 */
}
.task_area {
  width: 90%;
  margin: auto;
  height: calc(100vh - 200px);
}
.Audit_area {
  display: flex;
  justify-content: space-around;
}
.audit-list {
  display: flex;
  justify-content: space-between;
}
.topic {
  text-align: center;
  font-size: 40px;
  // padding: 20px 0;
  height: 100px;
  line-height: 100px;
  font-weight: 700;
}
.station_area {
  overflow-y: auto;
  margin-top: 20px;
  height: calc(100vh - 200px);
  .station_area_list {
    display: flex;
    justify-content: center;
    align-items: center;
    margin-bottom: 20px;
    .station_area_txt {
      font-size: 24px;
      min-width: 100px;
    }
  }
}

.el-header,
.el-footer {
  // background-color: #b3c0d1;
  color: #000;
  text-align: center;
  height: 30vh !important;
}

.el-aside {
  background-color: #d3dce6;
  color: #000;
  text-align: center;
  line-height: 200px;
}

.el-main {
  background-color: #e9eef3;
  color: #000;
  text-align: center;
  line-height: 160px;
  height: 70vh !important;
}

.top_area {
  display: flex;
  justify-content: center;
  align-items: center;
  height: calc(100vh - 200px);
  .top_left {
    margin-right: 180px;
  }
  .Call_Empty {
    font-size: 42px;
    font-weight: 500;
    margin-bottom: 30px;
  }
  .Call_Empty_num {
    display: flex;
    justify-content: center;
    font-size: 36px;
    font-weight: 600;
    // width: 120px;
    // height: 40px;
    border-radius: 10px;
    background-color: #b3c0d1;
    margin: auto;
    padding: 20px 20px;
  }
  .Current_Empties {
    font-size: 30px;
    font-weight: 600;
    margin-bottom: 8px;
  }
  .Current_Empties_num {
    font-size: 28px;
    font-weight: 600;
    text-align: right;
  }
  .submit {
    margin-top: 100px;
  }
}
</style>
